import 'dart:developer' as developer;

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_user_default_cache.dart';
import 'package:flutter_application_cyber/tools/cn_time.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart'
    as prefix;
import 'package:flutter_application_cyber/model/cn_strategy_vmodel.dart';
import '../../model/cn_strategy_model.dart';
import '../../tools/cn_style.dart';
import '../../tools/cn_message_item_factory.dart';
import '../../tools/cn_widget_util.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_AnchorViewModel.dart';
import '../../tools/cn_chartRechargeCard_message.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:provider/provider.dart';

class CnConversationItem extends StatefulWidget {
  late prefix.RCIMIWMessage message;
  CnConversationItemDelegate? delegate;
  bool? showTime;
  bool? multiSelect = false;
  List? selectedMessageIds;
  late _CnConversationItemState state;
  ValueNotifier<int?> time = ValueNotifier<int?>(0);

  CnConversationItem(
      CnConversationItemDelegate delegate,
      prefix.RCIMIWMessage msg,
      bool showTime,
      bool? multiSelect,
      List selectedMessageIds,
      ValueNotifier<int?> time) {
    this.message = msg;
    this.delegate = delegate;
    this.showTime = showTime;
    this.multiSelect = multiSelect;
    this.selectedMessageIds = selectedMessageIds;
    this.time = time;
  }

  @override
  State<StatefulWidget> createState() {
    return state = new _CnConversationItemState(this.delegate, this.message,
        this.showTime, this.multiSelect, this.selectedMessageIds, this.time);
  }

  void refreshUI(prefix.RCIMIWMessage message) {
    this.message = message;
    state._refreshUI(message);
  }
}

class _CnConversationItemState extends State<CnConversationItem> {
  String pageName = "example.CnConversationItem";
  prefix.RCIMIWMessage? message;
  CnConversationItemDelegate? delegate;
  bool? showTime;
  // example.UserInfo? user;
  Offset? tapPos;
  bool? multiSelect;
  bool isSeleceted = false;
  List? selectedMessageIds;
  SelectIcon? icon;

  ValueNotifier<int?> time = ValueNotifier<int>(0);
  bool needShowMessage = true;
  bool? showTranslateText = false;
  String translatedText = '';

  UserInfoModel getUserInfo() {
    return Provider.of<ChangeUserInfoModel>(context, listen: false).info;
  }

  _CnConversationItemState(
      CnConversationItemDelegate? delegate,
      prefix.RCIMIWMessage msg,
      bool? showTime,
      bool? multiSelect,
      List? selectedMessageIds,
      ValueNotifier<int?> time) {
    this.message = msg;
    this.delegate = delegate;
    this.showTime = showTime;
    // this.user = example.UserInfoDataSource.getUserInfo(msg.senderUserId);
    this.multiSelect = multiSelect;
    this.selectedMessageIds = selectedMessageIds;
    this.time = time;
    setInfo(message!.senderUserId);
    // needShowMessage = !(msg.direction == prefix.RCIMIWMessageDirection.receive);// && msg.content != null && msg.content!.destructDuration != null && msg.content!.destructDuration! > 0 && time.value == msg.content!.destructDuration);
  }

  void setInfo(String? targetId) async {
    // example.UserInfo? userInfo =
    //     example.UserInfoDataSource.cachedUserMap[targetId];
    // if (userInfo != null) {
    //   this.user = userInfo;
    // } else {
    //   example.UserInfo? userInfo =
    //       await example.UserInfoDataSource.getUserInfo(targetId);
    //   if (mounted) {
    //     setState(() {
    //       this.user = userInfo;
    //     });
    //   }
    // }

    bool value = await CnUserDefaultCacheHelper.getBoolValue('isAutoTranslate');
    if (value == true) {
      // __onTapedMesssage();
      translateRequest();
    }
  }

  @override
  void initState() {
    super.initState();
    bool isSelected = selectedMessageIds!.contains(message!.messageId);
    icon = SelectIcon(isSelected);
  }

  void _refreshUI(prefix.RCIMIWMessage msg) {
    // setState(() {
    this.message = msg;
    // 撤回消息的时候因为是替换之前的消息 UI ，需要整个刷新 item
    if (msg is prefix.RCIMIWRecallNotificationMessage) {
      setState(() {});
    }
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
      child: Column(
        children: <Widget>[
          this.showTime!
              ? CnWidgetUtil.buildMessageTimeWidget(message!.sentTime!)
              : CnWidgetUtil.buildEmptyWidget(),
          showMessage()
        ],
      ),
    );
  }

  Widget showMessage() {
    //属于通知类型的消息
    if (message is prefix.RCIMIWRecallNotificationMessage) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: Container(
          alignment: Alignment.center,
          constraints: BoxConstraints(
            maxWidth: RCLayout.MessageNotifiItemWidth,
            minHeight: RCLayout.MessageNotifiItemHeight,
          ),
          color: Color(RCColor.MessageTimeBgColor),
          child: Text(
            message!.direction == prefix.RCIMIWMessageDirection.send
                ? RCString.ConYouRecallMessageSuccess
                : getUserInfo().nickname! +
                    RCString.ConTargetRecallMessageSuccess,
            style: TextStyle(
                color: Colors.black, fontSize: RCFont.MessageNotifiFont),
            textAlign: TextAlign.center,
          ),
        ),
      );
    } else {
      if (multiSelect == true) {
        return GestureDetector(
          child: Row(
            children: <Widget>[mutiSelectContent(), subContent()],
          ),
          onTap: () {
            __onTapedItem();
          },
        );
      } else {
        return GestureDetector(
          child: Row(
            children: <Widget>[subContent()],
          ),
        );
      }
    }
  }

  Widget subContent() {
    if (message!.direction == prefix.RCIMIWMessageDirection.send) {
      return Expanded(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  Container(
                    alignment: Alignment.centerRight,
                    padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                    child: Text(getUserInfo().nickname ?? '',
                        style: TextStyle(
                            fontSize: RCFont.MessageNameFont,
                            color: Color(RCColor.MessageNameBgColor))),
                  ),
                  buildMessageWidget(),
                  Container(
                    alignment: Alignment.centerRight,
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTapDown: (TapDownDetails details) {
                        this.tapPos = details.globalPosition;
                      },
                      onTap: () {
                        __onTapedReadRequest();
                      },
                      child: message != null
                          ? Text("")
                          : buildReadInfo(), //&& message!.content!.destructDuration != null && message!.content!.destructDuration! > 0
                    ),
                  ),
                ],
              ),
            ),
            GestureDetector(
              onTap: () {
                __onTapedUserPortrait();
              },
              child: CnWidgetUtil.buildUserPortrait(getUserInfo().avatarUrl),
            ),
          ],
        ),
      );
    } else {
      return CnWidgetUtil.buildEmptyWidget();
    }
  }

  Widget translateText() {
    double screenWidth = MediaQuery.of(context).size.width;
    if ((message is prefix.RCIMIWTextMessage) && this.showTranslateText!) {
      return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(15, 4, 15, 0),
        child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Container(
                color: _getMessageWidgetBGColor(message!.direction!.index),
                constraints: BoxConstraints(
                  // 屏幕宽度减去头像宽度加上间距
                  maxWidth: screenWidth - 150,
                ),
                padding: EdgeInsets.all(10),
                child: Text(
                  translatedText,
                  style: TextStyle(fontSize: RCFont.MessageTextFont),
                ))),
      );
    } else {
      return Container();
    }
  }

  Widget mutiSelectContent() {
    // 消息是否添加
    // final alreadySaved = _saved.contains(message);
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
      child: icon,
    );
  }

  void __onTapedItem() {
    if (delegate != null) {
      delegate!.didTapItem(message);
      bool isSelected = selectedMessageIds!.contains(message!.messageId);
      icon!.updateUI(isSelected);
    } else {
      developer.log("没有实现 CnConversationItemDelegate", name: pageName);
    }
  }

  void __onTapedMesssage() {
    if (multiSelect == false) {
      // prefix.RCIMIWEngine.messageBeginDestruct(message!);

      translateRequest();
    }
    // return;
    if (delegate != null) {
      if (multiSelect == true) {
        //多选模式下修改为didTapItem处理
        delegate!.didTapItem(message);
        bool isSelected = selectedMessageIds!.contains(message!.messageId);
        icon!.updateUI(isSelected);
      } else {
        if (!needShowMessage) {
          needShowMessage = true;
          setState(() {});
        }
        delegate!.didTapMessageItem(message);
      }
    } else {
      developer.log("没有实现 CnConversationItemDelegate", name: pageName);
    }
  }

  void __onTapedReadRequest() {
    if (delegate != null) {
      // if (message!.readReceiptInfo != null && message!.readReceiptInfo!.isReceiptRequestMessage!) {
      //   delegate!.didTapMessageReadInfo(message);
      // } else {
      //   delegate!.didSendMessageRequest(message);
      // }
    } else {
      developer.log("没有实现 CnConversationItemDelegate", name: pageName);
    }
  }

  void __onLongPressMessage(Offset? tapPos) {
    if (delegate != null) {
      delegate!.didLongPressMessageItem(message, tapPos);
    } else {
      developer.log("没有实现 CnConversationItemDelegate", name: pageName);
    }
  }

  void __onTapedUserPortrait() {
    //点击头像，跳转主播详情页
    //获取官方账号消息
    bool isOfficialAccount = false;
    if (getStrategy().topOfficialUserIds.isNotEmpty) {
      for (int i = 0; i < getStrategy().topOfficialUserIds.length; i++) {
        String officialAccount = getStrategy().topOfficialUserIds[i];
        if (message!.senderUserId == officialAccount) {
          setState(() {
            isOfficialAccount = true;
          });
        }
      }
    }
    if (message!.senderUserId == getStrategy().userServiceAccountId) {
      setState(() {
        isOfficialAccount = true;
      });
    }

    if (isOfficialAccount == true) {
    } else {
      //  Navigator.of(context).pushNamed(
      //                     "/AnchorDetailsPage",
      //                     arguments: user!.id ,
      //                   );
    }
  }

  void translateRequest() {
    if (showTranslateText == false && (message is prefix.RCIMIWTextMessage)) {
      prefix.RCIMIWTextMessage? msg =
          widget.message as prefix.RCIMIWTextMessage?;

      // NetHelper.postTranslatorWithText(msg!.text!,(text, result, msg){

      //   if(result == true){
      //       setState(() {
      //       translatedText = text;
      //       showTranslateText = true;
      //       });
      //   }
      // });
    }
  }

  CnStrategyModel getStrategy() {
    return CnStrategyViewModel.getInfo().strategy!;
  }

  void __onLongPressUserPortrait(Offset? tapPos) {
    if (delegate != null) {
      delegate!.didLongPressUserPortrait(getUserInfo().userId, tapPos);
    } else {
      developer.log("没有实现 CnConversationItemDelegate", name: pageName);
    }
  }

  Widget buildMessageWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
            padding: EdgeInsets.fromLTRB(15, 4, 15, 0),
            alignment: message!.direction == prefix.RCIMIWMessageDirection.send
                ? Alignment.centerRight
                : Alignment.centerLeft,
            child: Row(
                mainAxisAlignment:
                    message!.direction == prefix.RCIMIWMessageDirection.send
                        ? MainAxisAlignment.end
                        : MainAxisAlignment.start,
                children: <Widget>[
                  message!.direction == prefix.RCIMIWMessageDirection.send &&
                          message !=
                              null //&& message!.content!.destructDuration != null && message!.content!.destructDuration! > 0
                      ? ValueListenableBuilder(
                          builder: (BuildContext context, int? value,
                              Widget? child) {
                            return Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                value! > 0
                                    ? Text(
                                        "$value ",
                                        style: TextStyle(color: Colors.red),
                                      )
                                    : Text("")
                              ],
                            );
                          },
                          valueListenable: time,
                        )
                      : Text(""),
                  // sentStatus = 20 为发送失败
                  message!.direction == prefix.RCIMIWMessageDirection.send &&
                          message!.sentStatus == prefix.RCIMIWSentStatus.failed
                      ? Container(
                          padding: EdgeInsets.fromLTRB(6, 6, 6, 6),
                          child: GestureDetector(
                              onTap: () {
                                if (delegate != null) {
                                  if (multiSelect == true) {
                                    //多选模式下修改为didTapItem处理
                                    delegate!.didTapItem(message);
                                    bool isSelected = selectedMessageIds!
                                        .contains(message!.messageId);
                                    icon!.updateUI(isSelected);
                                  } else {
                                    delegate!.didTapReSendMessage(message);
                                  }
                                }
                              },
                              child: Image.asset(
                                "images/rc_ic_warning.png",
                                width: RCLayout.MessageErrorHeight,
                                height: RCLayout.MessageErrorHeight,
                              )))
                      : CnWidgetUtil.buildEmptyWidget(),
                  Container(
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTapDown: (TapDownDetails details) {
                        this.tapPos = details.globalPosition;
                      },
                      onTap: () {
                        __onTapedMesssage();
                      },
                      onLongPress: () {
                        __onLongPressMessage(this.tapPos);
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: CnMessageItemFactory(
                            message: message, needShow: needShowMessage),
                      ),
                    ),
                  ),
                  message!.direction ==
                          prefix.RCIMIWMessageDirection
                              .receive // && message!.content != null && message!.content!.destructDuration != null && message!.content!.destructDuration! > 0
                      ? ValueListenableBuilder(
                          builder: (BuildContext context, int? value,
                              Widget? child) {
                            return Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                value! > 0
                                    ? Text(
                                        " $value",
                                        style: TextStyle(color: Colors.red),
                                      )
                                    : Text("")
                              ],
                            );
                          },
                          valueListenable: time,
                        )
                      : Text(""),
                ]),
          ),
        )
      ],
    );
  }

  Text? buildReadInfo() {
    if (message!.conversationType == prefix.RCIMIWConversationType.private) {
      if (message!.receivedStatus == prefix.RCIMIWReceivedStatus.read) {
        return Text("已读");
      }
      return Text("");
    }
    //  else if (message!.conversationType == prefix.RCConversationType.Group) {
    //   if (message!.readReceiptInfo != null && message!.readReceiptInfo!.isReceiptRequestMessage!) {
    //     if (message!.readReceiptInfo!.userIdList != null) {
    //       return Text("${message!.readReceiptInfo!.userIdList!.length}人已读");
    //     }
    //     return Text("0人已读");
    //   } else {
    //     if (canSendMessageReqdRequest()) {
    //       return Text("√");
    //     }
    //     return Text("");
    //   }
    // }
  }

  bool canSendMessageReqdRequest() {
    DateTime time = DateTime.now();
    int nowTime = time.millisecondsSinceEpoch;
    if (nowTime - message!.sentTime! < 120 * 1000) {
      return true;
    }
    return false;
  }

  Color _getMessageWidgetBGColor(int? messageDirection) {
    Color color = Color(RCColor.MessageSendBgColor);
    if (message!.direction == prefix.RCIMIWMessageDirection.receive) {
      color = Color(RCColor.MessageReceiveBgColor);
    }
    return color;
  }
}

abstract class CnConversationItemDelegate {
  //点击 item
  void didTapItem(prefix.RCIMIWMessage? message);

  //点击消息
  void didTapMessageItem(prefix.RCIMIWMessage? message);

  //长按消息
  void didLongPressMessageItem(prefix.RCIMIWMessage? message, Offset? tapPos);

  //点击用户头像
  void didTapUserPortrait(String userId);

  //长按用户头像
  void didLongPressUserPortrait(String? userId, Offset? tapPos);

  //发送消息已读回执请求
  void didSendMessageRequest(prefix.RCIMIWMessage? message);

  //点击消息已读人数
  void didTapMessageReadInfo(prefix.RCIMIWMessage? message);

  //点击消息已读人数
  void didTapReSendMessage(prefix.RCIMIWMessage? message);
}

// 多选模式下 cell 显示的 Icon
class SelectIcon extends StatefulWidget {
  bool? isSelected;
  late _SelectIconState state;

  SelectIcon(bool isSelected) {
    this.isSelected = isSelected;
  }

  @override
  _SelectIconState createState() => state = _SelectIconState(isSelected);

  void updateUI(bool isSelected) {
    this.state.refreshUI(isSelected);
  }
}

class _SelectIconState extends State<SelectIcon> {
  bool? isSelected;

  _SelectIconState(bool? isSelected) {
    this.isSelected = isSelected;
  }

  void refreshUI(bool isSelected) {
    setState(() {
      this.isSelected = isSelected;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Icon(
      isSelected! ? Icons.radio_button_checked : Icons.radio_button_unchecked,
      size: 20,
    );
  }
}
